/**
 * @desc: 添加商品弹框
 * @author: fj
 */
import React, { useState, useRef } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import FuzzyQueryStore from '@/components/FuzzyQueryStore';
// import FuzzyQueryGoods from '@/components/FuzzyQueryGoods';
import StoreGoodsSelect from './StoreGoodsSelect';
import SysGoodsSelect from './SysGoodsSelect';
import CommonTable from '@/components/CommonTable';
import { cloneDeep, isEmpty, find } from 'lodash';
import { getSpecList, getSysSpecList } from '../service';
import { Button, Form, Select, Checkbox, message } from 'antd';
import styles from './GoodsList.module.less';

const { Option } = Select;

const AddGoodsModal = ({ visible, handleCancel, handleOk }) => {
  const [form] = Form.useForm();
  const [goodsList, setGoodList] = useState([]); //搜索出来的商品
  const [storeGoodsInfo, storeSysGoodsInfo] = useState([]); //选中的系统商品信息
  const [sysGoodsInfo, setSysGoodsInfo] = useState([]); //选中的系统商品信息
  const [type, setType] = useState(1); //查询维度，默认为供应商
  const [storeId, setStoreId] = useState(undefined); //选中供应商id
  const [allChecked, setAllChecked] = useState(true); //全选状态
  const [loading, setLoading] = useState(false);

  const storeRef = useRef([]); //供应商商品的ref
  const sysRef = useRef([]); //系统商品的ref

  const columns = [
    //供应商列表
    {
      title: (
        <>
          <Checkbox
            onChange={(e) => changeAllChecked(e.target.checked)}
            checked={allChecked}
            disabled={isEmpty(goodsList)}
            className={styles.marginRight10}
          />
          尺码
        </>
      ),
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: (text, { sizeChecked }, index) => {
        return (
          <>
            <Checkbox
              onChange={(e) => changeSize(e.target.checked, index)}
              checked={sizeChecked}
              className={styles.marginRight10}
            />
            {text}
          </>
        );
      },
    },
    {
      title: '颜色',
      dataIndex: 'colorArr',
      key: 'colorArr',
      width: 480,
      render: (text, { colorArr = [] }, index) => {
        return (
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {colorArr.map((item, indexs) => {
              return (
                <span key={item.goodsId}>
                  <Checkbox
                    checked={item.colorChecked}
                    style={{ marginRight: 24 }}
                    onChange={(e) =>
                      changeColor(e.target.checked, index, indexs)
                    }
                  >
                    {item.color}
                  </Checkbox>
                </span>
              );
            })}
          </div>
        );
      },
    },
  ];

  const columns2 = [
    //系统列表
    {
      title: (
        <>
          <Checkbox
            onChange={(e) => changeAllChecked(e.target.checked)}
            checked={allChecked}
            disabled={isEmpty(goodsList)}
            className={styles.marginRight10}
          />
          尺码
        </>
      ),
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: (text, { sizeChecked }, index) => {
        return (
          <>
            <Checkbox
              onChange={(e) => changeSize(e.target.checked, index)}
              checked={sizeChecked}
              className={styles.marginRight10}
            />
            {text}
          </>
        );
      },
    },
    {
      title: '颜色+其他属性',
      dataIndex: 'colorArr',
      key: 'colorArr',
      width: 480,
      render: (text, { colorArr = [] }, index) => {
        return (
          <div style={{ display: 'flex', flexWrap: 'wrap' }}>
            {colorArr.map((item, indexs) => {
              return (
                <span key={item.id}>
                  <Checkbox
                    checked={item.colorChecked}
                    style={{ marginRight: 24 }}
                    onChange={(e) =>
                      changeColor(e.target.checked, index, indexs)
                    }
                  >
                    {item.customAtt
                      ? item.colorAtt + ';' + item.customAtt
                      : item.colorAtt}
                  </Checkbox>
                </span>
              );
            })}
          </div>
        );
      },
    },
  ];

  //尺码规格
  const changeSize = (checked, index) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource[index].sizeChecked = checked;
    const newArr = [];
    addDataSource[index].colorArr.map((item) => {
      newArr.push({
        ...item,
        colorChecked: checked,
      });
    });
    addDataSource[index].colorArr = newArr;
    setGoodList(addDataSource);
    const size_no = addDataSource.some((item) => item.sizeChecked == false);
    if (size_no) {
      setAllChecked(false);
    } else {
      setAllChecked(true);
    }
  };

  //颜色
  const changeColor = (checked, index, indexs) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource[index].colorArr[indexs].colorChecked = checked;
    if (checked) {
      const color_no = addDataSource[index].colorArr.some(
        (item) => item.colorChecked == false
      );
      if (color_no) {
        addDataSource[index].sizeChecked = false;
        setAllChecked(false);
      } else {
        addDataSource[index].sizeChecked = true;
        const size_no = addDataSource.some((item) => item.sizeChecked == false);
        if (size_no) {
          setAllChecked(false);
        } else {
          setAllChecked(true);
        }
      }
    } else {
      addDataSource[index].sizeChecked = false;
      setAllChecked(false);
    }
    setGoodList(addDataSource);
  };

  //全选反全选
  const changeAllChecked = (checked) => {
    const addDataSource = cloneDeep(goodsList);
    addDataSource.map((item) => {
      item.sizeChecked = checked;
      item.colorArr.map((items) => {
        items.colorChecked = checked;
      });
    });
    setGoodList(addDataSource);
    setAllChecked(checked);
  };

  //更改查询类型
  const handleChangeType = (val) => {
    setType(val);
    setGoodList([]);
  };

  // 查询
  const onFinish = async (value) => {
    setLoading(true);
    setGoodList([]);
    const addDataSource = [];
    if (type == 1) {
      //供应商商品
      const { storeGoodInfoList } = storeRef.current;
      const { goodsList } = storeGoodInfoList;
      const storeGoodInfo = find(goodsList, [
        'goodsCommonid',
        value.goodsCommonId,
      ]); //选中的供应商商品信息
      storeSysGoodsInfo(storeGoodInfo);
      const { data = {}, success } = await getSpecList(value);
      if (success) {
        Object.keys(data).forEach((item) => {
          //尺码
          const sizeStage = data[item];
          const colorArr = [];
          Object.keys(sizeStage).forEach((items) => {
            //颜色
            const colorStage = sizeStage[items];
            colorStage.map((child) => {
              colorArr.push({
                ...child,
                color: items,
                colorChecked: true,
              });
            });
          });
          addDataSource.push({
            size: item,
            sizeChecked: true,
            colorArr,
          });
        });
      }
    } else {
      //系统商品
      const { sysGoodInfoList } = sysRef.current;
      const { goodsList } = sysGoodInfoList;
      const sysGoodInfo = find(goodsList, ['spuId', value.spuId]); //选中的商品信息
      setSysGoodsInfo(sysGoodInfo);
      const { data = {}, success } = await getSysSpecList(value);
      if (success) {
        Object.keys(data).forEach((item) => {
          //尺码
          const sizeStage = data[item];
          const colorArr = [];
          Object.keys(sizeStage).forEach((items) => {
            //颜色
            const colorStage = sizeStage[items];
            colorStage.map((child) => {
              colorArr.push({ ...child, colorChecked: true });
            });
          });
          addDataSource.push({
            size: item,
            sizeChecked: true,
            colorArr,
          });
        });
      }
    }
    setGoodList(addDataSource);
    setAllChecked(true);
    setLoading(false);
  };

  //供应商改变
  const changeStore = (id) => {
    setStoreId(id);
    form.resetFields(['goodsCommonId']);
  };

  //供应商商品改变
  const changeGoods = (val) => {
    form.setFieldsValue({ goodsCommonId: val });
  };

  //系统商品改变
  const changeSysGoods = (val) => {
    form.setFieldsValue({ spuId: val });
  };

  //重置
  const onReset = () => {
    form.resetFields();
    setGoodList([]);
  };

  //点击取消
  const onCancel = () => {
    handleCancel();
  };

  //点击保存,添加商品
  const onSave = () => {
    if (loading) {
      return;
    }
    if (goodsList.length) {
      if (type == 1) {
        //供应商商品
        const arr = [];
        goodsList.map((item) => {
          item.colorArr.map((items) => {
            if (items.colorChecked) {
              arr.push({ ...items });
            }
          });
        });
        if (arr.length) {
          let goodsObj = {}; //单个添加商品的对象
          const colorObj = {}; //去重后商品的颜色
          const sizeObj = {}; //去重后商品的尺寸
          arr.forEach((t, index) => {
            if (!colorObj[t.color]) {
              colorObj[t.color] = {
                colorName: t.color,
                colorNum: 1,
              };
            } else {
              ++colorObj[t.color]['colorNum'];
            }
          });
          arr.forEach((t, index) => {
            if (!sizeObj[t.size]) {
              sizeObj[t.size] = {
                sizeName: t.size,
                sizeNum: 1,
              };
            } else {
              ++sizeObj[t.size]['sizeNum'];
            }
          });
          goodsObj = Object.assign(
            {
              customType: 'shop',
              sizeNum: Object.keys(sizeObj).length,
              colorNum: Object.keys(colorObj).length,
              goodsCount: 1, //每种规格的商品数量
              goodsNum: arr.length, // 颜色规格数
              storeGoodsArr: arr, //供应商商品数组
            },
            storeGoodsInfo
          );
          handleOk(goodsObj);
        } else {
          message.info('请选择尺码，颜色');
        }
      } else {
        //系统商品
        const sysGoodsArr = [];
        goodsList.map((item) => {
          item.colorArr.map((items) => {
            if (items.colorChecked) {
              sysGoodsArr.push({ ...items });
            }
          });
        });
        if (sysGoodsArr.length) {
          let goodsObj = {}; //单个添加商品的对象
          const colorObj = {}; //去重后商品的颜色
          const sizeObj = {}; //去重后商品的尺寸
          const otherObj = {}; //去重后商品的其他属性
          sysGoodsArr.forEach((t, index) => {
            if (!colorObj[t.colorAtt]) {
              colorObj[t.colorAtt] = {
                colorName: t.colorAtt,
                colorNum: 1,
              };
            } else {
              ++colorObj[t.colorAtt]['colorNum'];
            }
          });
          sysGoodsArr.forEach((t, index) => {
            if (!sizeObj[t.sizeAtt]) {
              sizeObj[t.sizeAtt] = {
                sizeName: t.sizeAtt,
                sizeNum: 1,
              };
            } else {
              ++sizeObj[t.sizeAtt]['sizeNum'];
            }
          });
          sysGoodsArr.forEach((t, index) => {
            if (t.customAtt != '') {
              //过滤空字符串的情况
              if (!otherObj[t.customAtt]) {
                otherObj[t.customAtt] = {
                  otherName: t.customAtt,
                  otherNum: 1,
                };
              } else {
                ++otherObj[t.customAtt]['otherNum'];
              }
            }
          });
          goodsObj = Object.assign(
            {
              customType: 'sys',
              sizeNum: Object.keys(sizeObj).length,
              colorNum: Object.keys(colorObj).length,
              otherNum: Object.keys(otherObj).length,
              goodsCount: 1, //每种规格的商品数量
              goodsNum: sysGoodsArr.length, // 颜色规格数
              sysGoodsArr: sysGoodsArr, //系统商品数组
            },
            sysGoodsInfo
          );
          handleOk(goodsObj);
        } else {
          message.info('请选择尺寸，颜色');
        }
      }
    } else {
      message.info('暂不支持该操作，请先检索供应商商品');
    }
  };

  //表格props
  const addTableProps = {
    data: goodsList,
    columns: type == 1 ? columns : columns2,
    scroll: { y: 480 },
  };

  return (
    <div>
      <CommonModal
        title={'添加商品'}
        visible={visible}
        onCancel={onCancel}
        width="848px"
        overflowY="hidden"
        footer={[
          <Button key="back" onClick={onCancel}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={onSave}>
            添加商品
          </Button>,
        ]}
      >
        <div>
          <Form
            layout={'inline'}
            className="search-form-style"
            form={form}
            onFinish={onFinish}
            style={{ marginBottom: '12px' }}
            name="batch-add-goods"
          >
            <Form.Item>
              <Select
                style={{ width: '120px' }}
                value={type}
                onChange={handleChangeType}
              >
                <Option value={1}>供应商维度</Option>
                <Option value={2}>系统商品维度</Option>
              </Select>
            </Form.Item>
            {type == 1 && (
              <>
                <Form.Item
                  label="供应商"
                  name="zjfStoreId"
                  rules={[{ required: true, message: '请先输入检索供应商' }]}
                >
                  <FuzzyQueryStore
                    style={{ width: '120px' }}
                    onChange={(e) => changeStore(e)}
                  />
                </Form.Item>
                <Form.Item
                  label="商品"
                  name="goodsCommonId"
                  rules={[{ required: true, message: '请输入商品名称' }]}
                >
                  {/* <FuzzyQueryGoods
                    width={200}
                    storeId={storeId}
                    onChange={(e) => changeGoods(e)}
                    type="spu"
                  /> */}
                  <StoreGoodsSelect
                    onChange={changeGoods}
                    storeId={storeId}
                    ref={storeRef}
                  />
                </Form.Item>
              </>
            )}
            {type == 2 && (
              <>
                <Form.Item
                  label="系统商品名称"
                  name="spuId"
                  rules={[{ required: true, message: '请输入系统商品名称' }]}
                >
                  <SysGoodsSelect onChange={changeSysGoods} ref={sysRef} />
                </Form.Item>
              </>
            )}
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                style={{ marginRight: '16px' }}
              >
                查询
              </Button>
              <Button onClick={onReset}>重置</Button>
            </Form.Item>
          </Form>
        </div>
        <CommonTable {...addTableProps} />
      </CommonModal>
      <CommonLoading loading={loading} />
    </div>
  );
};

export default React.memo(AddGoodsModal, (pre, next) => {
  if (pre.visible == next.visible) {
    return true;
  } else {
    return false;
  }
});
